package com.hxd.mall.utils.local

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import com.hxd.mall.constant.HxdGlobalInfo

/**
 * 缓存处理(不支持序列化，对象请存储为json串)
 */

object PrimaryUtil {
    private var sharedPreferences: SharedPreferences? = null
    private var editor: SharedPreferences.Editor? = null

    fun saveStringData(key: String, value: String) {
        initSharePreference()
        editor!!.putString(getKey(key), value).commit()
    }

    fun saveIntData(key: String, value: Int) {
        initSharePreference()
        editor!!.putInt(getKey(key), value).commit()
    }

    fun saveBooleanData(key: String, value: Boolean) {
        initSharePreference()
        editor!!.putBoolean(getKey(key), value).commit()
    }

    fun getBooleanData(key: String) = getBooleanData(key, false)

    fun getBooleanData(key: String, defaultValue: Boolean): Boolean {
        initSharePreference()
        return sharedPreferences!!.getBoolean(getKey(key), defaultValue)
    }

    fun getStringData(key: String): String {
        initSharePreference()
        return sharedPreferences!!.getString(getKey(key), "")!!
    }

    fun getStringData(key: String, defaultValue: String): String? {
        initSharePreference()
        return sharedPreferences!!.getString(getKey(key), defaultValue)
    }

    fun getIntData(key: String): Int {
        initSharePreference()
        return sharedPreferences!!.getInt(getKey(key), 0)
    }

    fun getIntData(key: String, defaultValue: Int): Int {
        initSharePreference()
        return if (!sharedPreferences!!.contains(getKey(key))) defaultValue else sharedPreferences!!.getInt(getKey(key), defaultValue)
    }

    fun deleteData(key: String) {
        initSharePreference()
        editor!!.remove(getKey(key)).commit()
    }

    fun clearAllData() {
        initSharePreference()
        editor!!.clear().commit()
    }

    @SuppressLint("CommitPrefEdits")
    private fun initSharePreference() {
        if (sharedPreferences == null) {
            sharedPreferences = HxdGlobalInfo.instance.applicationContext.getSharedPreferences("primary", Context.MODE_PRIVATE)
        }
        if (editor == null) {
            editor = sharedPreferences!!.edit()
        }
    }

    /**
     * 用户信息不需要添加passportID，其他添加，区分用户切换账号缓存
     * 避免更换手机号导致读取不到缓存
     */
    private fun getKey(key: String): String {
        return key
    }
}